import { createContext, useContext, useState } from "react";

// 1. 创建Context
const TODOContext = createContext();

export default function App() {
  const [list, setList] = useState([]);

  function addItem(item) {
    setList([...list, item]);
  }
  return (
    // 2. Context的提供者Provider
    <TODOContext.Provider
      value={{
        list,
        addItem,
      }}
    >
      <Todo> </Todo>
    </TODOContext.Provider>
  );
}

// 3. 创建Context
function Todo() {
  const { list, addItem } = useContext(TODOContext);
  const [text, setText] = useState("");
  const handleKeyUp = (event) => {
    if (event.code === "Enter") {
      addItem(text);
    }
  };
  return (
    <div>
      <input
        value={text}
        onChange={(event) => setText(event.target.value)}
        onKeyUp={handleKeyUp}
      ></input>
      <button onClick={() => addItem(text)}> 增加 </button>
      <ul>
        {list.map((item, index) => (
          <li key={index}> {item} </li>
        ))}
      </ul>
    </div>
  );
}
